<?php

namespace WebWeChat\WeChat;

use WebWeChat\Http\Request;

class WeChat
{
    //js登录
    const URL_WECHAT_JS_LOGIN  = 'https://login.weixin.qq.com/jslogin';
    //登录二维码
    const URL_WECHAT_QRCODE = 'https://login.weixin.qq.com/qrcode';
    //等待登录
    const URL_WECHAT_LOGIN  = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login';

    const URL_WECHAT_USER_INFO = 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit';

    protected $request = null;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取uuid
     * @param bool $refresh
     * @return mixed|string
     */
    public function getUUID($refresh = false)
    {
        $cacheFile = './../cache/uuid.txt';

        if ($refresh == false && file_exists($cacheFile)) {
            return file_get_contents($cacheFile);
        }

        $params = array(
            'appid' => 'wx782c26e4c19acffb',
            'fun'   => 'new',
            'lang'  => 'zh_CN',
            '_'     => time(),
            'redirect_uri' => 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage',
        );

        $url = self::URL_WECHAT_JS_LOGIN . '?' . http_build_query($params);

        $response = $this->request->request($url);

        $uuid = preg_replace('/.*"(.*)".*/', '$1', $response);

        file_put_contents($cacheFile, $uuid);

        return $uuid;
    }
    /**
     * 获取登录二维码
     *
     * @return string
     */
    public function getQrCode()
    {
        return self::URL_WECHAT_QRCODE . '/' . $this->getUUID(true);
    }

    /**
     * @param $uuid
     * @param int $tip
     * @return mixed
     */
    public function getLogin($uuid, $tip = 0)
    {
        $data = array(
            'tip'  => $tip,
            'uuid' => $uuid,
            '_'    => time(),
        );

        $response = $this->request->request(self::URL_WECHAT_LOGIN, $data);

        file_put_contents('log.txt', json_encode($response) . PHP_EOL, FILE_APPEND);

        //$arr = array_filter(explode(';', $response));
        //$status = preg_replace('/.*=([\d]{3}).*/', '$1', $response);

        preg_match('/.*=([\d]{3}).*/', $response, $matches);
        preg_match('/.*"(.*)"/', $response, $arr);

        $url = isset($arr[1]) ? $arr[1] : '';

       // var_dump($url);
        if ($url) {
            //parse_str(parse_url($url, PHP_URL_QUERY), $params);
            //file_put_contents('./../cache/cache.json', $params);

            $content = $this->request->request($url);
            $result  = json_encode(simplexml_load_string($content));
            $res = json_decode($result, true);

            file_put_contents('log.txt', $result . PHP_EOL , FILE_APPEND);
            //var_dump($res);
            if ($res['ret'] == 0) {
                file_put_contents('./../cache/cache.json', $result);
                return true;
            }
        }

        exit;

        return false;
    }

    public function getUserInfo()
    {
        $cache = json_decode(file_get_contents('./../cache/cache.json'), true);

        $data = array(
            "BaseRequest"=>array(
                "DeviceID"  => 'e839448193516470', //e + 15位随机数,
                "Sid"   => $cache['wxsid'],
                "Skey"  => $cache['skey'],
                "Uin"   => $cache['wxuin'],
            )
        );

        $response = $this->request->request(self::URL_WECHAT_USER_INFO, $data);

        return json_decode($response, true);
    }

}